//
//  UserSettingController.m
//  GIFShow
//
//  Created by lanou11air029 on 15/4/11.
//  Copyright (c) 2015年 CK. All rights reserved.
//

#import "UserSettingController.h"
#import "MySettingOptions.h"
#import "SwitchSettingCell.h"
#import <SDWebImage/SDImageCache.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import "UMFeedback.h"
#import "SettingTableController.h"
#import "NormalSetCell.h"
#import "GifCollectionViewController.h"
@interface UserSettingController ()
@property (strong, nonatomic) NSArray * array;
@property (strong, nonatomic) NSArray * imageNames;
@property (strong, nonatomic) NSMutableArray * heightArray;
@end

@implementation UserSettingController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.automaticallyAdjustsScrollViewInsets = YES;
        self.tabBarController.tabBar.hidden = NO;
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:2 inSection:1];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    });
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.translucent = NO;
    self.tableView.allowsMultipleSelection = NO;
    NSString * file = [MySettingOptions defaultOptions].backColor;
    if(self.view.frame.size.width == 375){
        NSString * back = [NSString stringWithFormat:@"%@6",file];
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:back]];
    }else{
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:file]];
    }
    self.refreshControl = [[UIRefreshControl alloc]init];
    NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIColor lightGrayColor] forKey:NSForegroundColorAttributeName];
    NSAttributedString * atrStr = [[NSAttributedString alloc]initWithString:@"更新缓存容量^_^" attributes:attributes];
    
    self.refreshControl.attributedTitle = atrStr;
    [self.refreshControl addTarget:self action:@selector(endRefreshed:) forControlEvents:UIControlEventValueChanged];
    
    self.array = @[@"设置",@"收藏",@"自动播放",@"消息推送",@"下载管理",@"清除离线数据",@"意见反馈",@"用户协议",@"关于我们"];
    self.imageNames = @[@"settingicon",@"setshoucang",@"autoplay",@"xiaoxi",@"xiazai",@"qingchu",@"fankui",@"xieyi",@"guanyuwomen"];
    
    [self.tableView registerClass:[SwitchSettingCell class] forCellReuseIdentifier:@"switchCell"];
    [self.tableView registerClass:[NormalSetCell class] forCellReuseIdentifier:@"normalCell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self myTheme];
    [[NSNotificationCenter defaultCenter]addObserverForName:@"ChangeTheme" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        [self myTheme];
    }];
    //    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)myTheme{
    NSString * file = [MySettingOptions defaultOptions].backColor;
    if(self.view.frame.size.width == 375){
        NSString * back = [NSString stringWithFormat:@"%@6",file];
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:back]];
    }else{
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:file]];
    }
}
-(void)endRefreshed:(UIRefreshControl *)refreshControl{
    [self.refreshControl endRefreshing];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row+indexPath.section*3 == 2 || indexPath.row+indexPath.section*3 == 3) {
        SwitchSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"switchCell" forIndexPath:indexPath];
        [self configCell:cell forIndexPath:indexPath];
        cell.backgroundColor = [UIColor colorWithWhite:1 alpha:0.9];
        cell.imageView.image = [UIImage imageNamed:self.imageNames[indexPath.section*3+indexPath.row]];
        return cell;
    }

    NormalSetCell * norcell = [tableView dequeueReusableCellWithIdentifier:@"normalCell" forIndexPath:indexPath];
    norcell.textTitleLabel.text = self.array[indexPath.row+indexPath.section*3];
    // Configure the cell...
    norcell.backgroundColor = [UIColor colorWithWhite:1 alpha:0.9];
    if (indexPath.row + indexPath.section*3 == 5) {
        norcell.title = @"清除离线数据";
        float filesize = [self cachesSize];
        norcell.rightDetailLabel.text = [NSString stringWithFormat:@"%.2fMB",filesize];
    }
    norcell.imageView.image = [UIImage imageNamed:self.imageNames[indexPath.section*3+indexPath.row]];
    return norcell;
}

-(void)configCell:(BaseSettingCell *)cell forIndexPath:(NSIndexPath *)indexPath{
    NSString * title = self.array[indexPath.row+indexPath.section*3];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.title = title;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height*0.03)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.heightArray) {
        self.heightArray = [[NSMutableArray alloc]init];
        for (int i = 0; i < 9; i++) {
            NSNumber * height = [NSNumber numberWithFloat:self.view.frame.size.height*0.085];
            [self.heightArray addObject:height];
        }
    }
    return [self.heightArray[indexPath.row + indexPath.section*3] floatValue];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return self.view.frame.size.height* 0.03;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row + indexPath.section *3 == 0){
        [self settingOP];
    }
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];

    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width*0.3 ,self.view.frame.size.height*0.1);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    if ([UIScreen mainScreen].bounds.size.height<=480) {
        flowLayout.itemSize = CGSizeMake(self.view.frame.size.width*0.3, self.view.frame.size.height*0.17);
    }
    if (indexPath.section*3+indexPath.row == 1) {
        GifCollectionViewController * gifCVC = [[GifCollectionViewController alloc]initWithCollectionViewLayout:flowLayout];
        gifCVC.isDownload = NO;
        gifCVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:gifCVC animated:YES];
    }
    if (indexPath.row + indexPath.section * 3 == 2||indexPath.row + indexPath.section * 3 == 3) {
        return;
    }
    [self.heightArray replaceObjectAtIndex:indexPath.row+indexPath.section*3 withObject:[NSNumber numberWithFloat:self.view.frame.size.height*0.085+20]];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(500 * USEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self tableView:tableView didDeselectRowAtIndexPath:indexPath];
    });
    if (indexPath.section*3+indexPath.row == 4) {
        GifCollectionViewController * gifCVC = [[GifCollectionViewController alloc]initWithCollectionViewLayout:flowLayout];
        gifCVC.hidesBottomBarWhenPushed = YES;
        gifCVC.isDownload = YES;
        [self.navigationController pushViewController:gifCVC animated:YES];
    }
    if (indexPath.row + indexPath.section * 3 == 5) {
        UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"清除全部离线数据？" message:@"你将清除所有缓存内容，包括图片和Gif" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self clearCaches];
        }];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        [alertC addAction:confirm];
        [alertC addAction:cancel];
        [self presentViewController:alertC animated:YES completion:nil];
    }
    if (indexPath.row + indexPath.section * 3 == 6) {
        [self feedBack];
    }
//    [self tableView:tableView didDeselectRowAtIndexPath:indexPath];
}
-(void)settingOP{
    SettingTableController * settingTC = [[SettingTableController alloc]initWithStyle:UITableViewStyleGrouped];
    settingTC.hidesBottomBarWhenPushed = YES;
    settingTC.navigationController.navigationBar.tintColor = [UIColor redColor];
    [self.navigationController pushViewController:settingTC animated:YES];
}
-(float)cachesSize{
    //    NSInteger imageCacheCount = [[SDImageCache sharedImageCache]getDiskCount];
    
    float sdwebImageCacheSize = [[SDImageCache sharedImageCache]getSize]/1024.0/1024;
    
    return sdwebImageCacheSize;
}
-(void)clearCaches{
  float sum = [self cachesSize];
    NSLog(@"%f",sum);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[SDImageCache sharedImageCache]cleanDiskWithCompletionBlock:^{
        NSLog(@"cleanDisk");
    }];
    [[SDImageCache sharedImageCache]clearDiskOnCompletion:^{
        NSLog(@"清除缓存");
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
    [self.tableView reloadData];
}
-(void)feedBack{
    self.automaticallyAdjustsScrollViewInsets = NO;
    [UMFeedback feedbackViewController].hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:[UMFeedback feedbackViewController] animated:YES];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row + indexPath.section * 3 == 2||indexPath.row + indexPath.section * 3 == 3) {
        return;
    }
    [self.heightArray replaceObjectAtIndex:indexPath.row+indexPath.section*3 withObject:[NSNumber numberWithFloat:self.view.frame.size.height*0.085]];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
